/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove.compiler;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.el.ELException;

import org.skatiger.jrove.Configurator;
import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.JroveHandler;
import org.skatiger.jrove.TagLibrary;
import org.skatiger.jrove.config.ConfigProperties;
import org.skatiger.jrove.tag.CompositeTagDecorator;
import org.skatiger.jrove.tag.CompositeTagLibrary;
import org.skatiger.jrove.tag.TagDecorator;
import org.skatiger.jrove.util.AssertUtil;
import org.skatiger.jrove.util.ClassUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class Compiler {
    static final String UI_LIBRARY_NAMESPACE = "http://jrove.skatiger.org/ui";

    protected final static Logger logger = LoggerFactory
            .getLogger(Compiler.class);
    private static final Object _initializingLock = new Object();
    private static final TagLibrary EMPTY_LIBRARY = new CompositeTagLibrary(
            new TagLibrary[0]);

    private static final TagDecorator EMPTY_DECORATOR = new CompositeTagDecorator(
            new TagDecorator[0]);

    private boolean validating = false;

    private boolean trimmingWhitespace = false;

    private boolean trimmingComments = false;

    private final List<TagLibrary> libraries = new ArrayList<TagLibrary>();

    private final List<TagDecorator> decorators = new ArrayList<TagDecorator>();

    private final Map<String, String> features = new HashMap<String, String>();

    private boolean initialized = false;

    /**
     * 
     */
    public Compiler() {
    }

    public final void addTagDecorator(TagDecorator decorator) {
        AssertUtil.notNull(decorator);
        if (!this.decorators.contains(decorator)) {
            this.decorators.add(decorator);
        }
    }

    public final void addTagLibrary(TagLibrary library) {
        AssertUtil.notNull(library);
        if (!this.libraries.contains(library)) {
            this.libraries.add(library);
        }
    }

    public final JroveHandler compile(URL src, String alias) throws IOException,
            ELException,
            JroveException {
        if (!this.initialized) {
            this.initialize();
        }
        return this.doCompile(src, alias);
    }

    public final TagDecorator createTagDecorator() {
        if (this.decorators.size() > 0) {
            return new CompositeTagDecorator(
                    (TagDecorator[]) this.decorators
                            .toArray(new TagDecorator[this.decorators.size()]));
        }
        return EMPTY_DECORATOR;
    }

    public final TagLibrary createTagLibrary() {
        if (this.libraries.size() > 0) {
            return new CompositeTagLibrary(
                    (TagLibrary[]) this.libraries
                            .toArray(new TagLibrary[this.libraries.size()]));
        }
        return EMPTY_LIBRARY;
    }

    protected abstract JroveHandler doCompile(URL src, String alias) throws IOException,
            ELException,
            JroveException;

    public final String getFeature(String name) {
        return (String) this.features.get(name);
    }

    public void initialize(Configurator configurator) {
        // load libraries
        List<TagLibrary> libs = configurator.getTagLibraries();
        for (TagLibrary lib : libs) {
            addTagLibrary(lib);
        }

        // load decorators
        String[] decorators = configurator.getTagDecorators();
        if (decorators.length > 0) {
            TagDecorator decObj;
            for (int i = 0; i < decorators.length; i++) {
                try {
                    decObj = (TagDecorator) ClassUtil.forName(decorators[i])
                            .newInstance();
                    addTagDecorator(decObj);
                    if (logger.isInfoEnabled()) {
                        logger.info("Successfully Loaded Decorator: "
                                + decorators[i]);
                    }
                } catch (Exception e) {
                    logger.warn("Error Loading Decorator: " + decorators[i], e);
                }
            }
        }

        // skip params?
        setTrimmingComments(configurator
                .getProperty(ConfigProperties.SKIP_COMMENTS));
        setTrimmingWhitespace(configurator
                .getProperty(ConfigProperties.SKIP_WHITESPACE));
    }

    private void initialize() {
        if (this.initialized) {
            return;
        }
        synchronized (_initializingLock) {
            if (logger.isInfoEnabled()) {
                logger.info("Initializing");
            }
            if (!this.createTagLibrary()
                    .containsNamespace(UI_LIBRARY_NAMESPACE)) {
                logger.error("Missing Built-in Tag Libraries! Make sure they are included within the META-INF/jrove directory of Jar");
            }
            this.initialized = true;
            if (logger.isInfoEnabled()) {
                logger.info("Initialization Successful");
            }
        }
    }

    public final boolean isTrimmingComments() {
        return this.trimmingComments;
    }

    public final boolean isTrimmingWhitespace() {
        return this.trimmingWhitespace;
    }

    public final boolean isValidating() {
        return this.validating;
    }

    public final void setFeature(String name, String value) {
        this.features.put(name, value);
    }

    public final void setTrimmingComments(boolean trimmingComments) {
        this.trimmingComments = trimmingComments;
    }

    public final void setTrimmingWhitespace(boolean trimmingWhitespace) {
        this.trimmingWhitespace = trimmingWhitespace;
    }

    public final void setValidating(boolean validating) {
        this.validating = validating;
    }
}
